<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="对话主题" prop="subject">
        <el-input
          v-model="queryParams.subject"
          placeholder="请输入对话主题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column label="记录编号" align="center" prop="id" width="200" show-overflow-tooltip />
      <el-table-column label="对话主题" align="center" prop="subject" min-width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" :formatter="dateFormatter" />
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 聊天记录弹窗 -->
  <Modal
    v-model:visible="chatHistoryVisible"
    title="对话详情"
    width="800px"
    :show-close="true"
    :close-on-click-modal="false"
    custom-class="chat-history-modal"
  >
    <ChatHistory
      v-if="chatHistoryVisible && currentHistoryId"
      :history-id="currentHistoryId"
      :chat-title="currentChatTitle"
    />
  </Modal>
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as AIChatApi from '@/api/member/aiChat'
import Modal from '@/components/Modal/index.vue'
import ChatHistory from '@/components/ChatHistory/index.vue'

interface UserAIChat {
  id: string
  subject: string
  createTime: number | string
  flowId?: string
  userId?: number
  tenantId?: number
}

const props = defineProps<{
  userId: number
}>()

const message = useMessage()

const loading = ref(true)
const total = ref(0)
const list = ref<UserAIChat[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  subject: undefined,
  createTime: undefined
})
const queryFormRef = ref()

// 聊天记录弹窗相关
const chatHistoryVisible = ref(false)
const currentHistoryId = ref('')
const currentChatTitle = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  console.log('开始获取AI对话记录列表，用户ID:', props.userId)
  try {
    const params: AIChatApi.AIChatPageReqVO = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      userId: props.userId
    }
    
    // 如果有主题筛选，添加subject参数
    if (queryParams.subject) {
      params.subject = queryParams.subject
    }
    
    // 如果有时间筛选，添加createTime参数
    if (queryParams.createTime && queryParams.createTime.length === 2) {
      params.createTime = queryParams.createTime
    }
    
    const data = await AIChatApi.getAIChatHistoryPage(params)
    
    console.log('API返回数据:', data)
    
    // axios响应拦截器已经解包了数据，直接使用data.list和data.total
    if (data && data.list) {
      list.value = data.list || []
      total.value = data.total || 0
      console.log('处理后的列表数据:', list.value)
      console.log('总数:', total.value)
    } else {
      console.log('API调用失败或数据格式不正确:', data)
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取AI对话记录列表失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查看对话记录 */
const handleView = (row: UserAIChat) => {
  if (!row || !row.id) {
    message.error('对话记录数据无效')
    return
  }
  
  currentHistoryId.value = row.id
  currentChatTitle.value = row.subject || '未知对话'
  chatHistoryVisible.value = true
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
// 聊天记录弹窗样式
:deep(.chat-history-modal) {
  .el-dialog {
    border-radius: 12px;
    overflow: hidden;
  }
  
  .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    background: #fafafa;
  }
  
  .el-dialog__body {
    padding: 0;
    height: 600px;
    overflow: hidden;
  }
}
</style> 
